//
//  AddAndDelTableViewController.m
//  11210
//
//  Created by student on 16/3/5.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "AddAndDelTableViewController.h"

@interface AddAndDelTableViewController ()
{
    BOOL isEable;
}
@property(nonatomic,strong)NSMutableArray *list;

@end

@implementation AddAndDelTableViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.list=[@[@"张三",@"李四",@"王五"] mutableCopy];
    
    UIBarButtonItem *btn=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(btnPressed)];
    self.navigationItem.rightBarButtonItem=btn;
    
}

-(void)btnPressed{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    [self.navigationItem.rightBarButtonItem setTitle:self.tableView.editing?@"完成":@"编辑"];
    if (self.tableView.editing && !isEable) {
        isEable=YES;
        NSIndexPath *tmpPath=[NSIndexPath indexPathForRow:self.list.count inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[tmpPath] withRowAnimation:UITableViewRowAnimationRight];
    }
    if (!self.tableView.editing && isEable) {
        isEable=NO;
        NSIndexPath *tmpPath=[NSIndexPath indexPathForRow:self.list.count inSection:0];
        [self.tableView deleteRowsAtIndexPaths:@[tmpPath] withRowAnimation:UITableViewRowAnimationRight];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isEable) {
        return self.list.count+1;
    }
    else{
    return self.list.count;
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.row==self.list.count)// && cell.textLabel.text==nil)
    {
        cell.textLabel.text=@"添加新同学";
    }else{
        cell.textLabel.text=self.list[indexPath.row];
    }

    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==self.list.count) {
        return UITableViewCellEditingStyleInsert;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.list removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
        [self.list addObject:[NSString stringWithFormat:@"新同学%li",self.list.count]];
        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }   
}

@end
